package com.duojuhe.common.utils.lockutil;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 锁工具类
 */
public class LockUtils {
    private final static Map<String, String> MAP = new ConcurrentHashMap<>();

    //tryLock(), 拿不到lock就返回失败
    public static boolean tryLock(String lockKey) {
       try {
           boolean flag = MAP.containsKey(lockKey);
           if (flag){
               return false;
           }
           MAP.put(lockKey,lockKey);
           return true;
       }catch (Exception e){
           return false;
       }
    }


    /**
     * 释放key，唤醒其他等待此key的线程
     */
    public static void unlock(String lockKey) {
        if (StringUtils.isNotBlank(lockKey)){
            MAP.remove(lockKey);
        }
    }
}
